package org.geektimes.projects.user.sql;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * DB 连接管理
 *
 * @author LiJun
 */
public  class DBConnectionManagerNew {

    /**
     * 删除用户表
     */
    public static final String DROP_USERS_TABLE_DDL_SQL = "DROP TABLE users";

    /**
     * 创建用户表
     */
    public static final String CREATE_USERS_TABLE_DDL_SQL = "CREATE TABLE users(" +
            "id INT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), " +
            "name VARCHAR(16) NOT NULL, " +
            "password VARCHAR(64) NOT NULL, " +
            "email VARCHAR(64) NOT NULL, " +
            "phoneNumber VARCHAR(64) NOT NULL" +
            ")";

    /**
     * 插入用户信息
     */
    public static final String INSERT_USER_DML_SQL = "INSERT INTO users(name,password,email,phoneNumber) VALUES " +
            "('A','******','a@gmail.com','1') , " +
            "('B','******','b@gmail.com','2') , " +
            "('C','******','c@gmail.com','3') , " +
            "('D','******','d@gmail.com','4') , " +
            "('E','******','e@gmail.com','5')";

    /**
     * 数据库链接
     */
    private Connection connection;

    /**
     * 默认构造
     */
    public DBConnectionManagerNew() {
        try{
            // 加载驱动
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            // 加载url
            String dbUrl = "jdbc:derby:/db/user-platform;create=true";
            connection = DriverManager.getConnection(dbUrl);

            // JNDI 获取 DB 链接 TODO
//            Context ctx = new InitialContext();
//            Context envCtx = (Context) ctx.lookup("java:comp/env");
//            DataSource ds = (DataSource)envCtx.lookup("jdbc/UserPlatformDB");
//            connection = ds.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 参数构造
     *
     * @param driver String
     * @param url String
     */
    public DBConnectionManagerNew(String driver, String url) {
    }



    /**
     * 设置数据库链接
     *
     * @param connection Connection
     */
    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    /**
     * 获取数据库链接
     *
     * @return Connection
     */
    public Connection getConnection() {
        return this.connection;
    }

    /**
     * 关闭数据库链接
     */
    public void releaseConnection() {
        if (this.connection != null) {
            try {
                this.connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e.getCause());
            }
        }
    }
}
